package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.IValueObject;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

/**
 * User: Sergey
 * Date: 29.07.11
 * Time: 17:32
 */
public class DBUtil<ID> {

    public List<IValueObject<ID, String>> queryForValueObjects(DataSource dataSource, String sql, String fieldId, Object... params) {
        JdbcTemplate template = new JdbcTemplate(dataSource);
        return template.query(sql, params, new ValueObjectRowMapper<ID>(fieldId));
    }

    public static String generateReferenceFieldName(String tableName, String idFieldName) {
        return tableName + "_" + idFieldName;

    }

    public static String generateCrossTableName(CollectionRegistry collectionRegistry, String collectionSourceId, String collectionDestinationId) {
        ICollection collectionSource = collectionRegistry.getCollection(collectionSourceId);
        ICollection collectionDestination = collectionRegistry.getCollection(collectionDestinationId);
        if (collectionSource instanceof IDBCollection && collectionDestination instanceof IDBCollection) {
            IDBCollection dbCollectionSource = (IDBCollection) collectionSource;
            IDBCollection dbCollectionDestination = (IDBCollection) collectionDestination;
            return dbCollectionSource.getTableName() + "_" + dbCollectionDestination.getTableName();
        }
        return null;
    }

    public static String getTableName(CollectionRegistry collectionRegistry, String collectionId) {
        ICollection collection = collectionRegistry.getCollection(collectionId);
        if (collection instanceof IDBCollection) {
            IDBCollection dbCollection = (IDBCollection) collection;
            return dbCollection.getTableName();
        }
        return null;
    }

}
